<!--
@description    表格展示
@author         秦俊强
@email          458112865@qq.com
@create         2021-06-07
-->

<template>
  <div class="content">
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="600"
      row-key="id"
      border
      stripe
      highlight-current-row
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      id="rebateSetTable"
    >
      <el-table-column
        v-for="(item, index) in tableHead"
        :key="index"
        :label="item.label"
        :property="item.prop"
        :align="index > 1 ? 'right' : ''"
      >
        <template slot-scope="scope">
          <div v-if="isArray(scope.row[scope.column.property])">
            <div
              v-for="(item, ind) in scope.row[scope.column.property]"
              :key="ind"
              :style="{ color: ind === 1 ? '#0AA372' : '' }"
            >
              <div v-if="isNumber(item)">
                <!--                <el-popover-->
                <!--                  placement="bottom-start"-->
                <!--                  width="160"-->
                <!--                  popper-class="area_popper"-->
                <!--                  trigger="click">-->
                <!--                  <div class="buttonClick">-->
                <!--                    <div>-->
                <!--                      <el-button size="mini" class="buttons" @click="userList">-->
                <!--                        <i class="el-icon-view"></i>-->
                <!--                        查看用户列表-->
                <!--                      </el-button>-->
                <!--                    </div>-->
                <!--&lt;!&ndash;                    <div>&ndash;&gt;-->
                <!--&lt;!&ndash;                      <el-button size="mini" class="buttons" @click="userPortrait">&ndash;&gt;-->
                <!--&lt;!&ndash;                        <i class="el-icon-map-location"></i>&ndash;&gt;-->
                <!--&lt;!&ndash;                        查看用户画像&ndash;&gt;-->
                <!--&lt;!&ndash;                      </el-button>&ndash;&gt;-->
                <!--&lt;!&ndash;                    </div>&ndash;&gt;-->
                <!--&lt;!&ndash;                    <div>&ndash;&gt;-->
                <!--&lt;!&ndash;                      <el-button size="mini" class="buttons" @click="userCluster">&ndash;&gt;-->
                <!--&lt;!&ndash;                        <i class="el-icon-user"></i>&ndash;&gt;-->
                <!--&lt;!&ndash;                        添加用户分群&ndash;&gt;-->
                <!--&lt;!&ndash;                      </el-button>&ndash;&gt;-->
                <!--&lt;!&ndash;                    </div>&ndash;&gt;-->

                <!--                    <div class="saveto" v-if="save">-->
                <!--                      <p style="color: rgba(0,0,0,.85);margin-left: 15px">保存为用户分群</p>-->
                <!--                      <el-divider></el-divider>-->
                <!--                      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">-->
                <!--                        <el-form-item label="显示名：" prop="name" style="text-align: left"></el-form-item>-->
                <!--                        <el-input v-model="ruleForm.showName" style="width: 250px" size="mini"-->
                <!--                                  placeholder="请输入分群显示名"></el-input>-->
                <!--                      </el-form>-->

                <!--                      <el-divider></el-divider>-->
                <!--                      <div class="but-bottom">-->
                <!--                        <el-button size="mini" @click="cancelOne">取消</el-button>-->
                <!--                        <el-button type="primary" size="mini">确定</el-button>-->
                <!--                      </div>-->
                <!--                    </div>-->
                <!--                  </div>-->
                <!--                </el-popover>-->
                <div class="jump" slot="reference">{{ item }}</div>
              </div>
              <div v-else>{{ item }}</div>
            </div>
          </div>

          <template v-else-if="isNumber(scope.row[scope.column.property])">
            <!--            <el-popover-->
            <!--              placement="bottom-start"-->
            <!--              width="160"-->
            <!--              popper-class="area_popper"-->
            <!--              trigger="click">-->
            <!--              <div class="buttonClick">-->
            <!--                <div>-->
            <!--                  <el-button size="mini" class="buttons" @click="userList">-->
            <!--                    <i class="el-icon-view"></i>-->
            <!--                    查看用户列表-->
            <!--                  </el-button>-->
            <!--                </div>-->
            <!--&lt;!&ndash;                <div>&ndash;&gt;-->
            <!--&lt;!&ndash;                  <el-button size="mini" class="buttons" @click="userPortrait">&ndash;&gt;-->
            <!--&lt;!&ndash;                    <i class="el-icon-map-location"></i>&ndash;&gt;-->
            <!--&lt;!&ndash;                    查看用户画像&ndash;&gt;-->
            <!--&lt;!&ndash;                  </el-button>&ndash;&gt;-->
            <!--&lt;!&ndash;                </div>&ndash;&gt;-->
            <!--&lt;!&ndash;                <div>&ndash;&gt;-->
            <!--&lt;!&ndash;                  <el-button size="mini" class="buttons" @click="userCluster">&ndash;&gt;-->
            <!--&lt;!&ndash;                    <i class="el-icon-user"></i>&ndash;&gt;-->
            <!--&lt;!&ndash;                    添加用户分群&ndash;&gt;-->
            <!--&lt;!&ndash;                  </el-button>&ndash;&gt;-->
            <!--&lt;!&ndash;                </div>&ndash;&gt;-->

            <!--                <div class="saveto" v-if="save">-->
            <!--                  <p style="color: rgba(0,0,0,.85);margin-left: 15px">保存为用户分群</p>-->
            <!--                  <el-divider></el-divider>-->
            <!--                  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">-->
            <!--                    <el-form-item label="显示名：" prop="name" style="text-align: left"></el-form-item>-->
            <!--                    <el-input v-model="ruleForm.showName" style="width: 250px" size="mini"-->
            <!--                              placeholder="请输入分群显示名"></el-input>-->
            <!--                  </el-form>-->

            <!--                  <el-divider></el-divider>-->
            <!--                  <div class="but-bottom">-->
            <!--                    <el-button size="mini" @click="cancelOne">取消</el-button>-->
            <!--                    <el-button type="primary" size="mini">确定</el-button>-->
            <!--                  </div>-->
            <!--                </div>-->
            <!--              </div>-->
            <!--              -->
            <!--            </el-popover>-->

            <div class="jump" slot="reference">
              {{ scope.row[scope.column.property] }}
            </div>
          </template>

          <div v-else>{{ scope.row[scope.column.property] }}</div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "table-funnel",

  props: {
    //计量单位 次 小时 天 无 四种情况
    measureTypeText: "",
    //通过什么查看
    byXXXReadValues: {
      type: Object,
      default: "",
    },
    ltvReportResData: {
      type: Object,
      default: null,
    },
    currentOverviewStep: {
      type: Number,
      default: 0,
    },
    //eventId
    currentEvent: {
      type: Object,
    },
    chodate: {
      type: Array,
    },
    measureType: {
      type: String,
    },
    select: {
      type: String,
    },
    filter: {
      type: Object,
    },
    userFilter: {
      type: Object,
    },
  },

  data() {
    return {
      tableHead: [],
      tableData: [],
      showtable: false,
      save: false,
      ruleForm: {
        showName: "",
      },
      rules: {
        showName: [
          { required: true, message: "请输入分群显示名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    let t = this;
    t.tableHead = [];
    t.tableData = [];

    t.initTabHead();
    t.$watch("ltvReportResData", () => {
      t.tableHead = [];
      t.tableData = [];
      t.initTabHead();
    });
  },

  activated() {
    //跳转页面不刷新
    this.userList();
    this.userPortrait();
  },

  methods: {
    exportExcel() {
      /* generate workbook object from table */
      let wb = XLSX.utils.table_to_book(
        document.querySelector("#rebateSetTable")
      );
      /* get binary string as output */
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "计算结果.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //查看用户列表
    userList() {
      console.log(this.query);
      this.$emit("getFilter");
      this.$router.push({
        path: "/dataAnalysis/pathAnalysis",
        query: {
          eventId: this.currentEvent.eventId,
          filter: this.filter,
          fromDate: this.chodate[0] ? this.chodate[0] : "",
          toDate: this.chodate[1] ? this.chodate[1] : "",
          measureType: this.measureType,
          rangeText: "",
          resultBucketParam: [],
          samplingFactor: 64,
          useCache: true,
          unit: this.select,
          userFilter: this.userFilter,
          timeZoneMode: "",
          serverTimeZone: "",
          rollupDate: false,
          sliceByValue: "2021-08-09",
          sliceFreq: 1,
          sliceMaxFreq: null,
          detail: true,
          sliceDate: [],
        },
      });
    },
    //查看用户画像
    userPortrait() {
      this.$router.push({
        path: "/dataAnalysis/pathAnalysis",
        query: {
          data: {
            appPushList: [],
            queryRequest: {
              eventId: this.currentEvent.eventId,
              filter: this.filter,
              fromDate: this.chodate[0] ? this.chodate[0] : "",
              toDate: this.chodate[1] ? this.chodate[1] : "",
              measureType: this.measureType,
              rangeText: "",
              resultBucketParam: [],
              samplingFactor: 64,
              useCache: true,
              unit: this.select,
              userFilter: this.userFilter,
              timeZoneMode: "",
              serverTimeZone: "",
              rollupDate: false,
              sliceByValue: "2021-08-09",
              sliceFreq: 1,
              sliceMaxFreq: null,
              detail: true,
              sliceByValues: [],
              sliceDate: [],
            },
            sourceType: 2,
            queryType: "ADDICTION",
            queryUrl: "",
          },
        },
      });
    },
    //添加用户分群
    userCluster() {
      this.save = !this.save;
    },
    cancelOne() {
      this.save = false;
    },
    tableDataRoute() {
      this.showtable = !this.showtable;
    },
    /*判断是否是数字*/
    isNumber(value) {
      return Object.prototype.toString.call(value) == "[object Number]";
    },
    /* 判断是否是数组 */
    isArray: (a) => {
      return Object.prototype.toString.call(a) === "[object Array]";
    },

    /* 初始化表头 趋势*/
    initTabHead() {
      let t = this;
      if (
        t.ltvReportResData.rows !== undefined &&
        t.ltvReportResData.rows.length > 0
      ) {
        t.tableHead.push({
          prop: "byValue",
          label:
            this.byXXXReadValues.cname === undefined
              ? ""
              : this.byXXXReadValues.cname,
        });
        t.tableHead.push({ prop: "totalPeople", label: "总人数" });
        let dates = t.ltvReportResData.rows[0].cells;
        for (let i = 0; i < dates.length; i++) {
          if (dates[i].bucketStart === 100) {
            t.tableHead.push({
              prop: "" + i,
              label:
                dates[i].bucketStart +
                "次以上" +
                "(含" +
                dates[i].bucketStart +
                t.measureTypeText +
                ")",
            });
          } else {
            t.tableHead.push({
              prop: "" + i,
              label:
                dates[i].bucketStart +
                t.measureTypeText +
                "~" +
                dates[i].bucketEnd +
                t.measureTypeText +
                "(不含" +
                dates[i].bucketEnd +
                t.measureTypeText +
                ")",
            });
          }
        }
        this.$forceUpdate();
        t.initTabData();
      }
    },

    /* 初始化表身数据 趋势*/
    initTabData() {
      let t = this;
      for (let i = 0; i < t.ltvReportResData.rows.length; i++) {
        let tabTem = t.getTabTem(true);
        if (t.ltvReportResData.rows[i].byValue === undefined) {
          tabTem.byValue = "未知";
        } else {
          tabTem.byValue = t.ltvReportResData.rows[i].byValue;
        }

        let itemEvent = t.ltvReportResData.rows[i];

        t.getRowDataAllDayEvent(tabTem, itemEvent.cells, true);

        tabTem["totalPeople"] = t.ltvReportResData.rows[i].totalPeople;
        t.tableData.push(tabTem);
      }

      this.$forceUpdate();

      // console.log('tableHead = ', t.tableHead);
      // console.log('tableData = ', t.tableData);
    },
    /* 返回数组字符串 例：['a', null] => 'a, null' */
    getByValuesListStr(arr) {
      let str = "";

      for (let i = 0; i < arr.length; i++) {
        let val = arr[i];
        str = str + val + (i === arr.length - 1 ? "" : ", ");
      }

      return str;
    },
    /* 返回表格行 */
    getRowDataAllDayEvent(resData, overview, needPrice) {
      for (let i = 0; i < overview.length; i++) {
        let item = overview[i];
        resData[i] = [item.people, item.percent + "%"];
      }
      return resData;
    },
    /* 返回表身数据模板 */
    getTabTem(b) {
      let tabTem = {};

      for (let i = 0; i < this.tableHead.length; i++) {
        let item = this.tableHead[i];

        // 标识唯一 id，方便折叠展开，和点击高亮行
        tabTem["id"] = Number(
          Math.random().toString().substr(3, 10) + Date.now()
        ).toString(36);

        if (item.prop) {
          tabTem[item.prop] = "";
        }

        if (b) {
          tabTem["children"] = [];
        }
      }

      return tabTem;
    },
  },
};
</script>

<style lang="scss" scoped>
.buttonClick {
  .buttons {
    width: 160px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 0;
    background: #272727;
    color: white;
  }
}

.jump {
  text-decoration: underline;
  cursor: pointer;
}

.saveto {
  width: 350px;
  height: 180px;
  position: absolute;
  border-radius: 4px;
  left: 200px;
  top: 100px;
  z-index: 100;
  box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
    0 2px 4px 0 rgba(232, 237, 250, 0.5);
  background: #ffffff;

  .but-bottom {
    display: flex;
    justify-content: flex-end;
    margin: 10px;
  }

  .demo-ruleForm {
    margin-left: 50px;
    margin-bottom: 15px;
    width: 320px;
    justify-content: left;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>


<style>
.el-popover[x-placement^="bottom"] .popper__arrow {
  border-bottom-color: #272727 !important;
}

.el-popover[x-placement^="bottom"] .popper__arrow::after {
  border-bottom-color: #272727 !important;
}

.area_popper {
  offset: left;
  background-color: #272727 !important;
  border-color: #272727 !important;
}

::v-deep .el-table tbody td {
  padding: 5px 0;
}

.el-divider--horizontal {
  margin: 0 !important;
}

.el-form-item {
  margin-bottom: 0 !important;
  width: 80%;
}
</style>
